package n16_共享模型内存_有序性和可见性;

import lombok.extern.slf4j.Slf4j;
import utils.Sleeper;

/**
 * @author fu
 * @date 2022-01-13 20:41
 * 概要：
 * ---------------------------------------------------------------
    synchronized 也能保证 共享变量的可见性
    synchronized会创建 Monitor
    volatile 更轻量级，推荐使用
 * |=============================================================
 */
@Slf4j(topic = "c.T1")
public class T2_退不出的循环_by_synchronized {


    static boolean run = true;
    final static Object lock = new Object();


    public static void main(String[] args) throws InterruptedException {

        Thread t = new Thread(()->{

            while(true){
                // ....
                synchronized (lock) {
                    if(!run)break;
                }

            }
        });
        t.start();

        Sleeper.sleep(1);
        log.debug("一秒后 改为 false， 但是 t线程的循环 不会停止！");
        synchronized (lock) {
            run = false; // 线程t不会如预想的停下来
        }
    }
}
